from functools import wraps

from flask import request, jsonify

from app.middlerware.Jwt import UserToken


def permission(config):
    def login_required(func):
        @wraps(func)
        def wrapper(*args,**kwargs):
            try:
                header = request.headers
                token = header.get("token")
                if token is  None:
                    return jsonify(dict(code=401,msg='认证失败'))
                user_info = UserToken.parse_token(token)

                kwargs["user_info"] = user_info
            except Exception as e:
                return jsonify(dict(code=401, msg=str(e)))

            if user_info.get("role",0) < config.role:
                return jsonify(dict(code=400,msg="对不起, 你没有足够的权限"))
            return func(*args,**kwargs)

        return wrapper
    return login_required
